<template>
  <div class="editor-container">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      style="height: 300px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      mode="default"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const valueHtml = ref('')

// 自定义上传图片和视频
const MAX_IMAGE_SIZE = 10 * 1024 * 1024
const MAX_VIDEO_SIZE = 100 * 1024 * 1024
const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']

const validateMediaFile = (file) => {
  if (!file) return false
  if (file.type?.startsWith('image/')) {
    if (file.size > MAX_IMAGE_SIZE) {
      ElMessage.error('图片大小不能超过 10MB')
      return false
    }
    if (!ALLOWED_IMAGE_TYPES.includes(file.type)) {
      ElMessage.error('仅支持 JPG/PNG/GIF/WEBP 图片')
      return false
    }
  }
  if (file.type?.startsWith('video/') && file.size > MAX_VIDEO_SIZE) {
    ElMessage.error('视频大小不能超过 100MB')
    return false
  }
  return true
}

const customUpload = async (file, insertFn) => {
  if (!validateMediaFile(file)) {
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    const response = await axios.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.code === 1) {
      // 修改这里，直接使用 localhost 而不是带端口的地址
      insertFn(`${response.data.data.filePath}`)
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(response.data.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 工具栏配置
const toolbarConfig = {
  excludeKeys: []
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `/upload`,
      fieldName: 'file',
      customUpload,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      maxFileSize: 10 * 1024 * 1024, // 10MB
      allowedFileTypes: ['image/*']
    },
    uploadVideo: {
      server: `/upload`,
      fieldName: 'file',
      customUpload,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      maxFileSize: 100 * 1024 * 1024, // 100MB
      allowedFileTypes: ['video/*']
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 初始化编辑器
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 编辑器内容变化时触发
const handleChange = (editor) => {
  emit('update:modelValue', editor.getHtml())
}

// 监听传入的值变化
watch(() => props.modelValue, (val) => {
  if (val !== valueHtml.value) {
    valueHtml.value = val
  }
}, { immediate: true })
</script>

<style>
.editor-container {
  border: 1px solid #ccc;
  z-index: 100;
}
</style>
